from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import ListView
from django.core.mail import send_mail

from blog.models import Post, Comment
from blog.forms import EmailPostForm, CommentForm
from taggit.models import Tag
# Create your views here.


class PostListView(ListView):
    # queryset 变量查询所有已发布的文章，如果通过model=Post，会使用Post.objects.all()查询获得所有文章
    queryset = Post.published.all()
    paginate_by = 3
    # 设置posts为模板变量的名称，如果不设置默认变量名称是object_list
    context_object_name = "posts"
    template_name = "list.html"


def post_list(request, tag_slug=None):
    object_list = Post.published.all()
    tag = None
    if tag_slug:
        tag = get_object_or_404(Tag, slug=tag_slug)
        object_list = object_list.filter(tags__in=[tag])

    paginator = Paginator(object_list, 3)            # 每页显示三篇文章
    page = request.GET.get('page', 1)
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        # 如果page参数不是一个整数的就返回第一页
        posts = paginator.page(1)
    except EmptyPage:
        # 如果超出总页数就返回最后一页
        posts = paginator.page(paginator.num_pages)
    count = Post.objects.count()
    return render(request, "list.html", {"posts": posts, "page": page,
                                         "tag": tag, "count": count})


def post_detail(request, year, month, day, slug):

    post = get_object_or_404(Post, status="published", publish__year=year,
                             publish__month=month, publish__day=day, slug=slug)
    # 列出文章对应的所有活动的评论
    # comments = Comment.objects.filter(post=post, active=True)
    comments = post.comments.filter(active=True)

    new_comment = None

    if request.method == "POST":
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            # 通过表单直接创建新的数据对象,但是并不保存到数据库中
            new_comment = comment_form.save(commit=False)
            # 设置外键为当前文章
            new_comment.post = post
            new_comment.save()
    else:
        comment_form = CommentForm()
    return render(request, "detail.html", {"post": post, "comments": comments,
                                           "comment_form": comment_form,
                                           "new_comment": new_comment})


def post_share(request, post_id):
    """分享文章"""
    # 通过id获取post对象
    post = get_object_or_404(Post, id=post_id, status="published")
    sent = False
    if request.method == "POST":
        # 表单被提交
        form = EmailPostForm(request.POST)
        # 调用表单的is_vaild方法，这个方法会验证表单中所有数据是否有效，
        # 如果有任意字段未通过验证，此时可以在form.errors属性中查看错误信息
        # 如果表单验证失败，form.cleaned_data只会包含通过验证的数据
        if form.is_valid():
            # 验证表单数据
            cd = form.cleaned_data
            # 发送邮件
            # build_absolute_uri 生成完整的url
            post_url = request.build_absolute_uri(post.get_absolute_url())
            subject = "{}({})分享給你閱讀{}".format(cd["name"], cd["email"], post.title)
            message = "阅读文章“{}”, 问章的url：{}".format(post.title, post_url)
            send_mail(subject, message, "yangguanyu_2006@126.com", [cd["to"]])
            sent = True

    else:
        form = EmailPostForm()
    return render(request, "share.html", {"form": form, "post": post, "sent": sent})
